import socket
import threading

Img_Size = 10240

output_mod = True


class Connection:
    # 本机IP和端口地址
    cmd_ip = None
    cmd_port = 8889

    # Tello命令端口
    tello_ip = '192.168.10.1'
    tello_port = 8889

    # 状态流端口
    msg_ip = '0.0.0.0'
    msg_port = 8890

    # 视频流端口
    video_ip = '0.0.0.0'
    video_port = 11111

    cmd_sock = None
    msg_sock = None
    video_sock = None

    def start(self):
        self.cmd_thread.start()

    def cmd_send(self):
        while True:
            # print(self.cmd_in.get())
            get = self.cmd_in.get()
            self.send(cmd=get[0])
            while get[1] == 1:
                try:
                    self.cmd_out.put(self.rec_result())
                    get[1] = 0
                except socket.timeout:
                    self.send(cmd=get[0])

    def __init__(self, cmd_in=None, cmd_out=None):
        self.cmd_in = cmd_in
        self.cmd_out = cmd_out
        self.cmd_thread = threading.Thread(target=self.cmd_send)

        # 检查套接字是否已经绑定
        self.cmd_ip = (socket.gethostbyname(socket.gethostname()))
        # self.cmd_ip = '192.168.10.2'
        self.cmd_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  # socket for sending cmd
        # Connection.cmd_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.cmd_sock.bind((self.cmd_ip, self.cmd_port))
        self.cmd_sock.settimeout(8)

        self.msg_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  # socket for sending cmd
        # Connection.msg_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.msg_sock.bind((self.msg_ip, self.msg_port))

        self.video_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  # socket for sending cmd
        # Connection.video_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.video_sock.bind((self.video_ip, self.video_port))

    def rec_result(self):
        rec = self.cmd_sock.recvfrom(1024)[0].decode('utf-8')
        if output_mod:
            print(" *** : ", rec)
        return rec

    def rec_msg(self):
        return self.msg_sock.recvfrom(1024)

    def rec_video(self):
        return self.video_sock.recvfrom(Img_Size)

    def send(self, cmd=""):
        if output_mod:
            print(" *** send: ", cmd)
        self.cmd_sock.sendto(cmd.encode('gbk'), (self.tello_ip, self.tello_port))

    def send_ESP32(self, cmd=""):
        cmd = "EXT " + cmd
        if output_mod:
            print(" *** send: ", cmd)
        self.cmd_sock.sendto(cmd.encode('gbk'), (self.tello_ip, self.tello_port))
